import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
// 导入静态数据 - 已禁用
// import { inboundListData, inboundDetailListData, supplierListData } from '@/data/inbound'

// 恢复/添加 API 导入
import {
  getInboundList as fetchInboundList,
  getInboundDetail as fetchInboundDetail,
  createInbound as createInboundApi,
  updateInbound as updateInboundApi,
  updateInboundStatus as updateInboundStatusApi,
  cancelInbound as cancelInboundApi,
  receiveInbound as receiveInboundApi,
  putawayInbound as putawayInboundApi,
  getReceivingTasks as fetchReceivingTasks, // Keep if used
  getPutawayTasks as fetchPutawayTasks, // Keep if used
  deleteInbound as deleteInboundApi
} from '@/api/inbound' // Verify API path
import supplierApi from '@/api/supplier' // Import supplierApi object

export const useInboundStore = defineStore('inbound', () => {
  // 状态定义
  const inboundList = ref([])
  const inboundDetail = ref(null) // Initialize as null
  const detailList = ref([]) // Keep if components use it directly
  const supplierList = ref([]) // State to hold supplier list
  const receivingTasks = ref([]) // Keep if used
  const putawayTasks = ref([]) // Keep if used
  const loading = ref(false)
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const currentInboundDetail = ref(null)
  
  // 添加统计数据的state
  const inboundStatistics = ref({
    pendingReceipt: 0,   // 待收货
    pendingPutaway: 0,   // 待上架
    completedToday: 0,   // 今日完成
    exceptionOrders: 0,  // 异常单据
    totalOrders: 0,      // 总单据数
    totalQuantity: 0,    // 总商品数
    monthlyTrend: [],    // 月度趋势
    statusDistribution: [] // 状态分布
  });

  // --- 状态映射函数定义在 setup 内部 ---

  // 获取入库单状态对应颜色
  const getInboundStatusColor = (status) => {
    const statusMap = {
      0: 'red',     // 已取消
      1: 'orange',  // 待收货
      2: 'blue',    // 待上架
      3: 'green'    // 已完成
    };
    
    const statusNum = parseInt(status);
    if (!isNaN(statusNum) && statusMap[statusNum]) {
      return statusMap[statusNum];
    }
    
    // 兼容字符串状态
    if (status === 'cancelled') return 'red';
    if (status === 'waiting_receive') return 'orange';
    if (status === 'waiting_putaway') return 'blue';
    if (status === 'completed') return 'green';
    
    return 'gray'; // 未知状态
  };

  // 获取入库单状态对应文本
  const getInboundStatusText = (status) => {
    const statusMap = {
      0: '已取消',
      1: '待收货',
      2: '待上架',
      3: '已完成'
    };
    
    const statusNum = parseInt(status);
    if (!isNaN(statusNum) && statusMap[statusNum]) {
      return statusMap[statusNum];
    }
    
    // 兼容字符串状态
    if (status === 'cancelled') return '已取消';
    if (status === 'waiting_receive') return '待收货';
    if (status === 'waiting_putaway') return '待上架';
    if (status === 'completed') return '已完成';

    return status ? `状态${status}` : '未知状态';
  };

  // 获取入库单列表
  async function getInboundList(params = {}) {
    try {
      loading.value = true;

      // --- 使用真实 API 调用 ---
      const response = await fetchInboundList({
        page: pagination.value.current,
        pageSize: pagination.value.pageSize,
        ...params
      });
      // --- API 调用结束 ---

      /* --- 禁用静态数据 ---
      const response = { code: 200, data: inboundListData }
      --- 静态数据结束 --- */

      // 使用后端API的成功状态码 0
      if (response.code === 0) {
        // 获取入库单列表
        let list = response.data.list || [];
        
        // 应用排序逻辑
        inboundList.value = sortInboundList(list);
        
        pagination.value = {
          current: response.data.page || pagination.value.current,
          pageSize: response.data.pageSize || pagination.value.pageSize,
          total: response.data.total || 0
        };

        // 自动获取统计数据
        await getInboundStatistics();
        
        // 添加成功提示
        const message = inboundList.value.length > 0 ? '入库单列表获取成功' : '暂无入库单数据';
        Message.success(message);
        return response.data;
      } else {
        Message.error(response.message || '获取入库单列表失败');
        inboundList.value = [];
        pagination.value.total = 0;
        return null;
      }
    } catch (error) {
      console.error('获取入库单列表失败:', error);
      Message.error('获取入库单列表时发生错误'); // 更通用的错误消息
      inboundList.value = [];
      pagination.value.total = 0;
      throw error; // Rethrow for component to potentially handle
    } finally {
      loading.value = false;
    }
  }
  
  // 对入库单列表按业务优先级和时间排序
  function sortInboundList(list) {
    // 业务状态优先级顺序: 待上架(2) > 待收货(1) > 已完成(3) > 已取消(0)
    const statusPriority = {
      2: 0, // 待上架 - 最高优先级
      1: 1, // 待收货 - 次高优先级
      3: 2, // 已完成 - 较低优先级
      0: 3  // 已取消 - 最低优先级
    };
    
    return [...list].sort((a, b) => {
      // 首先按状态优先级排序
      const statusA = Number(a.status);
      const statusB = Number(b.status);
      
      const priorityA = statusPriority[statusA] !== undefined ? statusPriority[statusA] : 999;
      const priorityB = statusPriority[statusB] !== undefined ? statusPriority[statusB] : 999;
      
      if (priorityA !== priorityB) {
        return priorityA - priorityB;
      }
      
      // 如果状态相同，则按预计到货时间降序排序（近期的排在前面）
      const timeA = a.expected_time ? new Date(a.expected_time).getTime() : 0;
      const timeB = b.expected_time ? new Date(b.expected_time).getTime() : 0;
      
      if (timeA && timeB) {
        return timeA - timeB; // 升序排列，近期的排在前面
      }
      
      // 如果没有预计到货时间，则按创建时间降序排序
      const createTimeA = a.created_at ? new Date(a.created_at).getTime() : 0;
      const createTimeB = b.created_at ? new Date(b.created_at).getTime() : 0;
      
      return createTimeB - createTimeA; // 降序排列，最新创建的排在前面
    });
  }

  // 获取入库统计数据
  async function getInboundStatistics() {
    try {
      // 后端API暂不可用，使用前端计算的数据
      const waitingReceive = inboundList.value.filter(item => item.status === 1).length;
      const waitingPutaway = inboundList.value.filter(item => item.status === 2).length;
      const completed = inboundList.value.filter(item => item.status === 3).length;
      const cancelled = inboundList.value.filter(item => item.status === 0).length;
      
      // 计算今日完成的入库单数
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayCompleted = inboundList.value.filter(item => {
        if (item.status === 3) { // 已完成状态
          const updateTime = new Date(item.updated_at || item.created_at);
          return updateTime >= today;
        }
        return false;
      }).length;
      
      // 计算异常单据数（修改为统计已取消的订单）
      const exceptionCount = cancelled;
      
      // 更新统计数据
      inboundStatistics.value = {
        pendingReceipt: waitingReceive,
        pendingPutaway: waitingPutaway,
        completedToday: todayCompleted,
        exceptionOrders: exceptionCount,
        totalOrders: inboundList.value.length,
        totalQuantity: inboundList.value.reduce((sum, order) => 
          sum + (order.items ? order.items.length : 0), 0),
        // 月度趋势数据 - 使用固定模拟数据避免空图表
        monthlyTrend: [
          { month: '11月', count: 46 },
          { month: '12月', count: 12 },
          { month: '1月', count: 48 },
          { month: '2月', count: 14 },
          { month: '3月', count: 28 },
          { month: '4月', count: 56 }
        ],
        // 状态分布数据
        statusDistribution: [
          { status: '待收货', value: waitingReceive || 1 },
          { status: '待上架', value: waitingPutaway || 1 },
          { status: '已完成', value: completed || 1 },
          { status: '已取消', value: cancelled || 1 }
        ]
      };
      
      console.log('入库统计数据更新:', inboundStatistics.value);
      return inboundStatistics.value;
    } catch (error) {
      console.error('获取入库统计数据失败:', error);
      // 出错时返回一些默认数据，确保UI不会崩溃
      return {
        pendingReceipt: 0,
        pendingPutaway: 0,
        completedToday: 0,
        exceptionOrders: 0,
        totalOrders: 0,
        totalQuantity: 0,
        monthlyTrend: [
          { month: '11月', count: 46 },
          { month: '12月', count: 12 },
          { month: '1月', count: 48 },
          { month: '2月', count: 14 },
          { month: '3月', count: 28 },
          { month: '4月', count: 56 }
        ],
        statusDistribution: [
          { status: '待收货', value: 1 },
          { status: '待上架', value: 1 },
          { status: '已完成', value: 1 },
          { status: '已取消', value: 1 }
        ]
      };
    }
  }

  // 移除帮助函数：将中文状态转换为英文键值
  /*
  function convertStatus(statusText) { ... }
  */

  // 获取入库单详情
  async function getInboundDetail(id) {
     if (!id) {
         console.warn('getInboundDetail called with invalid id');
         return null;
     }
    try {
      loading.value = true
      inboundDetail.value = null; // Reset before fetching
      detailList.value = []; // Reset before fetching

       // --- 使用真实 API 调用 ---
      const response = await fetchInboundDetail(id);
      // --- API 调用结束 ---

      /* --- 禁用静态数据 ---
      const mainData = inboundListData.list.find(item => item.id === id) || {};
      const details = inboundDetailListData[id] || [];
      const response = { code: 200, data: { ...mainData, details: details } }
       --- 静态数据结束 --- */

      // 使用后端API的成功状态码 0
      if (response.code === 0 && response.data) {
        inboundDetail.value = response.data; // Store the whole detail object
        // Assuming backend detail includes items list as 'items'
        detailList.value = response.data.items || [];
        return response.data;
      } else {
        Message.error(response.message || '获取入库单详情失败');
        return null;
      }
    } catch (error) {
      console.error('获取入库单详情失败:', error);
      Message.error('获取入库单详情失败');
      throw error; // Re-throw error
    } finally {
      loading.value = false;
    }
  }

  // 创建入库单 (切换到 API, 检查状态码)
  async function createInbound(data) {
    try {
      loading.value = true
      console.log('Store: 创建入库单请求数据:', data);
      
      // --- 使用真实 API 调用 ---
      const response = await createInboundApi(data)
      console.log('Store: 创建入库单API响应:', response);
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      if (response.code === 0) { // Check success code 0
        console.log('Store: 创建入库单成功', response.data);
        // 成功时添加success字段为true，保持格式一致
        return { ...response.data, success: true };
      } else {
        console.error('Store: 创建入库单失败', response.message);
        // 返回错误信息而不是直接显示Message
        return { success: false, message: response.message || '创建入库单失败' };
      }
    } catch (error) {
      console.error('Store: 创建入库单错误:', error);
      return { success: false, message: error.message || '创建入库单失败，请检查网络连接' };
    } finally {
      loading.value = false;
    }
  }

  // 更新入库单 (切换到 API, 检查状态码)
  async function updateInbound(id, data) {
     if (!id) return null;
    try {
      loading.value = true
      // --- 使用真实 API 调用 ---
      const response = await updateInboundApi(id, data)
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      if (response.code === 0) { // Check success code 0
        Message.success('更新入库单成功');
        // getInboundDetail(id); // Optionally refresh detail
        return response.data;
      } else {
        Message.error(response.message || '更新入库单失败');
        return null;
      }
    } catch (error) {
      console.error('更新入库单失败:', error);
      Message.error('更新入库单失败');
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 审核入库单 (切换到 API, 如果后端提供此接口)
  async function approveInbound(id) {
    // Assuming an API like `approveInboundApi(id)` exists
    // If not, this function might need removal or modification
    if (!window.approveInboundApi) { // Temporary check if API exists
        Message.warn('approveInbound API function not found or implemented');
        return false;
    }
    try {
      loading.value = true;
      // --- 使用真实 API 调用 ---
      // const response = await approveInboundApi(id); // Uncomment if API exists
      const response = { code: 0, message: '审核成功(模拟)'}; // Placeholder if no API yet
      // --- API 调用结束 ---
      /* --- 禁用静态数据 ---
      const response = { code: 200, data: true }
      if (index > -1) { inboundList.value[index].status = 'approved'; }
      --- 静态数据结束 --- */

      if (response.code === 0) { // Check success code 0
        Message.success('审核入库单成功');
        // getInboundList(); // Refresh list after approval
        return true;
      } else {
        Message.error(response.message || '审核入库单失败');
        return false;
      }
    } catch (error) {
      console.error('审核入库单失败:', error);
      Message.error('审核入库单失败');
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 取消入库单 (修复 API 调用和 Message 方法)
  async function cancelInbound(id) {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 --- 
      // 假设 cancelInboundApi 发送类似 POST /inventory/inbound/{id}/cancel 的请求
      const response = await cancelInboundApi(id); 
      // --- API 调用结束 --- 
      
      // 移除占位符检查
      /* 
       if (!window.cancelInboundApi) { 
          Message.warning('cancelInbound API function not found or implemented'); // Corrected to warning
          return { success: false, message: '前端接口未实现' }; // Return structured object
      }
      const response = { code: 0, message: '取消成功(模拟)'}; 
      */

      if (response.code === 0) { 
        // 刷新列表数据 (Store 内部可能也需要更新状态，如果列表依赖 Store)
        await getInboundList(); // 假设 store 内部有自己的刷新逻辑
        return { success: true }; // 返回成功状态
      } else {
        // 移除这里的 Message 调用
        // const message = response.message || '取消失败';
        // Message.warning(message); 
        return { success: false, message: response.message || '取消失败' }; // 返回失败状态和消息
      }
    } catch (error) {
      console.error('取消入库单失败:', error);
      const errorMsg = error.response?.data?.message || error.message || '取消操作时发生错误';
      // 移除这里的 Message 调用
      // const message = error.response?.data?.msg || '取消操作失败';
      // Message.warning(message); 
      return { success: false, message: errorMsg }; // 返回失败状态和消息
    } finally {
      loading.value = false;
    }
  }

  // 更新入库单状态
  async function updateInboundStatus(id, status) {
    if (!id) {
      console.error('updateInboundStatus: 未提供入库单ID');
      Message.error('操作失败：无效的入库单ID');
      return null;
    }

    // 确保ID为字符串格式
    const orderId = String(id);
    // 将status转换为字符串格式，因为后端需要字符串格式的状态码
    const statusStr = String(status);
    
    console.log(`准备更新入库单状态：ID=${orderId}, 状态码=${statusStr}`);

    try {
      loading.value = true;
      
      console.log(`updateInboundStatus: 调用API更新订单 ${orderId} 的状态为: ${statusStr}`);

      // 调用API，发送字符串格式的状态码
      const response = await updateInboundStatusApi(orderId, statusStr);
      console.log('API响应:', response);

      if (response && response.code === 0) {
        Message.success('入库单状态更新成功');
        // 可以选择性地在这里更新 Store 中的 inboundDetail 状态，以便 UI 立即响应
        if (inboundDetail.value && inboundDetail.value.id === id) {
            inboundDetail.value.status = status; // 更新本地状态为数字状态码
        }
        return response.data || true;
      } else {
        const errorMsg = response?.message || '更新入库单状态失败';
        console.error('更新状态失败:', errorMsg, response);
        Message.error(errorMsg);
        return null;
      }
    } catch (error) {
      console.error('更新入库单状态失败:', error);
      let errorMsg = '更新入库单状态失败';
      
      if (error.response && error.response.data) {
        errorMsg = error.response.data.message || errorMsg;
        console.error('服务器返回错误:', error.response.data);
      } else if (error.message) {
        errorMsg = error.message;
      }
      
      // 显示更详细的错误信息
      console.error('错误详情:', {
        url: error.config?.url || '未知',
        method: error.config?.method || '未知',
        status: error.response?.status || '未知',
        data: error.response?.data || '未知'
      });
      
      Message.error(errorMsg);
      return null;
    } finally {
      loading.value = false;
    }
  }

  // 收货操作
  async function receiveInbound(id, data) {
    try {
      loading.value = true;
      
      console.log('收货操作，参数:', id, data);
      
      // 简单参数验证
      if (!id) {
        throw new Error('入库单ID不能为空');
      }
      
      if (!data || !data.items || !Array.isArray(data.items) || data.items.length === 0) {
        throw new Error('收货商品数据不能为空');
      }
      
      // 数据验证
      data.items.forEach(item => {
        if (!item.order_item_id) {
          throw new Error('订单项ID不能为空');
        }
        if (!item.received_quantity || item.received_quantity <= 0) {
          throw new Error('收货数量必须大于0');
        }
      });
      
      // 添加autoUpdateStatus参数，默认为false，防止自动更新入库单状态
      // 只有在用户点击"完成收货"按钮时才将此参数设为true
      if (!data.autoUpdateStatus) {
        // 添加参数，告诉后端不要自动更新入库单状态
        data.preserveStatus = true;
      }
      
      // 调用API
      const response = await receiveInboundApi(id, data);
      
      // 严格检查API返回状态
      if (!response) {
        console.error('收货操作失败: 无响应');
        return Promise.reject(new Error('收货失败: 服务器无响应'));
      }
      
      if (response.code !== 0) {
        console.error('收货操作失败:', response);
        return Promise.reject(new Error(response.message || '收货失败'));
      }
      
      // 成功情况下返回true
      console.log('收货操作成功:', response);
      return true;
    } catch (error) {
      console.error('收货操作异常:', error);
      
      // 错误信息处理
      let errorMsg = '收货操作失败';
      if (error.response && error.response.data) {
        errorMsg = error.response.data.message || errorMsg;
      } else if (error.message) {
        errorMsg = error.message;
      }
      
      return Promise.reject(new Error(errorMsg));
    } finally {
      loading.value = false;
    }
  }

  // 上架操作
  async function putawayInbound(id, data) {
    // 验证入库单ID和上架数据
    if (!id) {
      Message.error('入库单ID无效');
      return null;
    }
    
    // 确认数据结构正确
    const requestData = data;
    
    // 数据结构验证
    if (!requestData || !requestData.items || !Array.isArray(requestData.items) || requestData.items.length === 0) {
      Message.error('无效的上架数据');
      return null;
    }

    // 验证每个上架项的必要字段
    for (const item of requestData.items) {
      if (!item.order_item_id || !item.location_id || item.putaway_quantity === undefined || item.putaway_quantity <= 0) {
        Message.error('上架项数据无效');
        return null;
      }
    }

    try {
      loading.value = true;
      const response = await putawayInboundApi(id, requestData);
      
      if (response.code === 0) {
        // 将英文 success 改为中文成功提示
        Message.success(response.message || '上架操作成功');
        return response.data || true;
      } else {
        const errorMsg = response.message || '上架操作失败';
        Message.error(errorMsg);
        return null;
      }
    } catch (error) {
      // 尝试从错误响应中获取具体信息
      let errorMsg = '上架操作失败';
      
      if (error.response) {
        // 服务器返回了响应但状态码不是2xx
        try {
          if (error.response.data) {
            if (typeof error.response.data === 'string') {
              // 尝试解析JSON字符串
              try {
                const errorData = JSON.parse(error.response.data);
                errorMsg = errorData.message || errorData.error || errorMsg;
              } catch (e) {
                // 如果不是JSON，直接使用字符串
                errorMsg = error.response.data.length > 100 
                  ? error.response.data.substring(0, 100) + '...' 
                  : error.response.data;
              }
            } else if (error.response.data.message) {
              errorMsg = error.response.data.message;
            } else if (error.response.data.error) {
              errorMsg = error.response.data.error;
            }
          }
        } catch (parseError) {
          // 解析错误响应失败
        }
      } else if (error.request) {
        // 请求已发送但没有收到响应
        errorMsg = '服务器无响应，请检查网络连接';
      } else {
        // 请求配置出错
        errorMsg = error.message || '请求配置错误';
      }
      
      Message.error(errorMsg);
      return null;
    } finally {
      loading.value = false;
    }
  }

  // 获取待收货任务 (切换到 API, 需要后端实现)
  async function getReceivingTasks() {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 ---
      const response = await fetchReceivingTasks(); // Assuming API exists
      // --- API 调用结束 ---
      /* --- 禁用静态数据 ---
      const tasks = inboundList.value.filter(...).map(...);
      const response = { code: 200, data: tasks }
      --- 静态数据结束 --- */

      if (response.code === 0) { // Check success code 0
        receivingTasks.value = response.data || [];
        return response.data;
      } else {
        Message.error(response.message || '获取待收货任务失败');
        return [];
      }
    } catch (error) {
      console.error('获取待收货任务失败:', error);
      Message.error('获取待收货任务失败');
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 获取待上架任务 (切换到 API, 需要后端实现)
  async function getPutawayTasks() {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 ---
      const response = await fetchPutawayTasks(); // Assuming API exists
      // --- API 调用结束 ---
      /* --- 禁用静态数据 ---
      const tasks = inboundList.value.filter(...).map(...);
      const response = { code: 200, data: tasks }
       --- 静态数据结束 --- */

      if (response.code === 0) { // Check success code 0
        putawayTasks.value = response.data || [];
        return response.data;
      } else {
        Message.error(response.message || '获取待上架任务失败');
        return [];
      }
    } catch (error) {
      console.error('获取待上架任务失败:', error);
      Message.error('获取待上架任务失败');
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 获取供应商列表 (Fix API call)
  async function getSupplierList() {
    try {
      loading.value = true;
      // --- 使用真实 API 调用 --- 
      // Use the imported object and its method
      const response = await supplierApi.getSupplierList(); 
      // --- API 调用结束 ---
      /* --- 禁用静态数据 --- */

      if (response.code === 0) { // Check success code 0
        // Assuming API response structure is { code: 0, data: [...] } or { code: 0, data: { list: [...] } }
        // Adjust .data or .data.list based on actual response
        supplierList.value = response.data.list || response.data || []; 
        return response.data;
      } else {
        Message.error(response.message || '获取供应商列表失败');
        return []; // Return empty array on failure
      }
    } catch (error) {
      console.error('获取供应商列表失败:', error);
      Message.error('获取供应商列表失败');
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 确保返回所有需要暴露的状态和方法
  return {
    inboundList,
    inboundDetail,
    detailList,
    supplierList,
    receivingTasks,
    putawayTasks,
    loading,
    pagination,
    currentInboundDetail,
    inboundStatistics,
    getInboundList,
    getInboundDetail,
    createInbound,
    updateInbound,
    approveInbound,
    cancelInbound,
    receiveInbound,
    putawayInbound,
    getReceivingTasks,
    getPutawayTasks,
    getSupplierList,
    updateInboundStatus,
    deleteInbound: deleteInboundApi,
    getInboundStatusColor,
    getInboundStatusText,
    getInboundStatistics,
    sortInboundList // 导出排序函数，以便其他组件可能使用
  }
}) 